//===================================================================================
// $$
//
// Coder: Code Milker v1.0
// 0 - EntityName
// 1 - lower
//===================================================================================


namespace App.Data.SqlServer.Repositories {
    using System;
    using System.Collections.Generic;
    using System.Data;
    using System.Linq;
    using App.Model;

    public class NewsRepository : BaseRepository, INewsRepository {
        public NewsRepository(IUnitOfWork unitOfWork)
            : base(unitOfWork) {
        }
        public void Create(News news) {
            this.GetDbSet<News>().Add(news);
            this.UnitOfWork.SaveChanges();
        }

        public News GetNews(Guid newsId) {
            return this.GetDbSet<News>()
                .Where(c => c.Id == newsId)
                .Single();
        }

        public void Update(News updatedNews) {
            this.GetDbSet<News>().Attach(updatedNews);
            this.SetEntityState(updatedNews, updatedNews.Id == Guid.Empty
                ? EntityState.Added
                : EntityState.Modified);
            this.UnitOfWork.SaveChanges();
        }

        public void Delete(Guid newsId) {
            News NewsToDelete = this.GetNews(newsId);
            this.GetDbSet<News>().Remove(NewsToDelete);
            this.UnitOfWork.SaveChanges();
        }

        public IQueryable<News> Find() {
            return this.GetDbSet<News>();
        }

        public IQueryable<News> GetAll()
        {
            return this.GetDbSet<News>().OrderByDescending(i=>i.PostedOn);
        }
    }
}
